﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace YiTian.Core.Modularity
{
    public class ModuleDiscoverer : IModuleDiscoverer
    {
        public List<Assembly> Discover(string moduleDirectory, string dllNamePattern)
        {
            if (!Directory.Exists(moduleDirectory))
            {
                throw new DirectoryNotFoundException($"模块目录不存在：{moduleDirectory}");
            }

            var assemblyList = new List<Assembly>();
            var dllPaths = Directory.EnumerateFiles(moduleDirectory, dllNamePattern, SearchOption.TopDirectoryOnly);

            foreach (var dllPath in dllPaths)
            {
                try
                {
                    // 加载程序集（避免重复加载）
                    var assemblyName = AssemblyName.GetAssemblyName(dllPath);
                    var existingAssembly = AppDomain.CurrentDomain.GetAssemblies()
                        .FirstOrDefault(asm => asm.FullName == assemblyName.FullName);

                    if (existingAssembly != null)
                    {
                        assemblyList.Add(existingAssembly);
                    }
                    else
                    {
                        // 加载外部程序集（注意：.NET Core中需使用AssemblyLoadContext）
                        var assembly = Assembly.LoadFrom(dllPath);
                        assemblyList.Add(assembly);
                    }
                }
                catch (Exception ex)
                {
                    // 记录日志：加载DLL失败（如非.NET程序集、损坏文件等）
                    Console.WriteLine($"加载模块DLL失败：{dllPath}，错误：{ex.Message}");
                }
            }

            return assemblyList;
        }
    }
}
